package csv_to_json

import (
	"encoding/csv"
	"encoding/json"
	"os"
)

type Option struct {
	Value    string    `json:"value"`
	Label    string    `json:"label"`
	Level    string    `json:"level"`
	Parent   string    `json:"parent"`
	Children []*Option `json:"children"`
}

type Options []*Option

func (op Options) CreateTree() (result Options) {
	var recursion func(option *Option)

	recursion = func(option *Option) {
		for _, item := range op {
			if item.Parent == option.Value {
				recursion(item)
				option.Children = append(option.Children, item)
			}
		}
	}

	for _, item := range op {
		if item.Level == "1" {
			recursion(item)
			result = append(result, item)
		}
	}
	return
}

type CsvItem struct {
}

// 将爬取到的数据转换成element级联选择器的数据结构
func CsvToJson(path string, toPath string) (err error) {
	csvData, err := ReadCsvFile(path)
	if err != nil {
		panic(err)
	}

	var options Options

	for index, line := range csvData {
		if index == 0 {
			continue
		}
		options = append(options, &Option{
			Value:    line[0],
			Label:    line[1],
			Parent:   line[2],
			Level:    line[3],
			Children: nil,
		})
	}

	treeData := options.CreateTree()
	//fmt.Println(treeData)
	b, err := json.Marshal(treeData)
	if err != nil {
		return
	}
	f, _ := os.OpenFile(toPath, os.O_CREATE|os.O_WRONLY, 0)
	defer f.Close()
	_, err = f.Write(b)
	return
}

func ReadCsvFile(filename string) ([][]string, error) {
	// Open CSV file
	fileContent, err := os.Open(filename)
	if err != nil {
		return [][]string{}, err
	}
	defer fileContent.Close()

	// Read File into a Variable
	lines, err := csv.NewReader(fileContent).ReadAll()
	if err != nil {
		return [][]string{}, err
	}
	return lines, nil
}
